package com.codemonkey.lq.tools;

import java.io.File;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StringUtil;

/**
 * 一个很神奇的错误
 *		[WARNING] The POM for org.ow2.asm:asm-commons:jar:5.2 is invalid, transitive dependencies (if any) will not be available: 1 problem was encountered while building the effective model
 *		[FATAL] Non-parseable POM C:\Users\LQ\.m2\repository\org\ow2\asm\asm-commons\5.2\asm-commons-5.2.pom: start tag not allowed in epilog but got p (position: END_TAG seen ...ARE, EVEN IF ADVISED OF\n ! THE POSSIBILITY OF SUCH DAMAGE.\n-->\n\n<p... @82:3)  @ line 82, column 3
 * 自己這邊的原因是 因爲错误中提示的文件里相同的配置出现了两次, 也就是会有两个<project>节点。
 * 因此写下本脚本来辅助完成删除工作
 * @author lq
 *
 */
public final class MvnRemoveTool {

	private static final String MAVEN_PATH = "c:\\Users\\LQ\\.m2\\repository";

	public static void main(String[] args) {

		findAndDelete(FileUtil.file(MAVEN_PATH));
	}

	public static boolean findAndDelete(File file) {
		if (!file.exists()) {
		} else if (file.isFile()) {
			if (file.getName().endsWith(".pom")) {
				Console.log("check file [ {} ]", file.getAbsolutePath());
				removeSpecialTag(file, "<project>");
				removeSpecialTag(file, "<project ");
				removeSpecialTag(file, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

				return true;
			}
		} else if (file.isDirectory()) {
			File[] files = file.listFiles();
			for (File f : files) {
				if (findAndDelete(f)) {
					break;
				}
			}
		}
		return false;
	}

	private static final void removeSpecialTag(final File file, final String tagContent) {
		Console.log("deal file [ {} ] by tag [ {} ]", file.getName(), tagContent);

		final String content = FileUtil.readString(file, CharsetUtil.UTF_8);
		// TODO  <project xxxx>	
		int count = StringUtil.count(content, tagContent);
		if (count > 1) {
			int lastIndexOfIgnoreCase = StringUtil.lastIndexOfIgnoreCase(content, tagContent);
			String saved = StringUtil.sub(content, 0, lastIndexOfIgnoreCase);
			Console.log("the part is [ {} ]", StringUtil.sub(content, lastIndexOfIgnoreCase,
					lastIndexOfIgnoreCase + 20));
			FileUtil.writeString(saved, file, CharsetUtil.UTF_8);
		}
	}

}
